// 激光狙击手精英敌机类
import { TimeManager } from './TimeManager.js';


const maxDistance = 10000
export class EnemyLaserSniper {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.width = 60;  // 比普通敌机更大
        this.height = 60;
        this.speed = 40;  // 移动较慢，更重装甲
        
        // 生命值系统
        this.maxHp = 10;   // 需要10发子弹才能击毁
        this.hp = this.maxHp;
        
        // 激光攻击系统
        this.isCharging = false;
        this.chargeTime = 0;
        this.chargeDuration = 1500; // 1.5秒蓄力时间
        this.lastAttackTime = 0;
        this.attackCooldown = 4000; // 4秒攻击冷却
        this.postFireDelay = 0; // 发射后停顿时间
        this.postFireDuration = 500; // 0.5秒停顿
        this.targetX = 0; // 瞄准的目标X位置
        this.targetY = 0; // 瞄准的目标Y位置
        this.predictedPlayerX = 0; // 预测的玩家位置
        this.predictedPlayerY = 0;
        
        // 视觉特效
        this.enginePulse = 0;
        this.shieldPulse = 0;
        this.rotationAngle = 0;
        this.damageFlash = 0; // 受伤闪烁效果
        this.chargePulse = 0; // 蓄力特效
        
        // 激光瞄准线
        this.aimLineAlpha = 0;
        this.aimLineIntensity = 0;
    }
    
    update(deltaTime, player) {
        // 更新发射后停顿时间
        if (this.postFireDelay > 0) {
            this.postFireDelay = TimeManager.updateTimer(this.postFireDelay, deltaTime);
        }
        
        // 只有在不进行攻击且不在发射后停顿时才移动
        if (!this.isCharging && this.postFireDelay <= 0) {
            // 基于时间的移动计算
            this.y += this.speed * (deltaTime / 1000);
        }
        
        // 更新视觉特效
        this.enginePulse = TimeManager.updatePhase(this.enginePulse, deltaTime, 8);
        this.shieldPulse = TimeManager.updatePhase(this.shieldPulse, deltaTime, 4);
        this.rotationAngle = TimeManager.updatePhase(this.rotationAngle, deltaTime, 1);
        
        // 更新受伤闪烁
        if (this.damageFlash > 0) {
            this.damageFlash = TimeManager.updateTimer(this.damageFlash, deltaTime);
        }
        
        // 攻击逻辑
        const laserData = this.updateAttackLogic(deltaTime, player);
        
        return laserData; // 返回激光数据供游戏主循环处理
    }
    
    updateAttackLogic(deltaTime, player) {
        const currentTime = Date.now();
        
        // 检查是否可以开始攻击
        if (!this.isCharging && player && 
            currentTime - this.lastAttackTime >= this.attackCooldown) {
            
            // 开始蓄力，预测玩家位置
            this.startCharging(player);
        }
        
        // 更新蓄力过程
        if (this.isCharging) {
            this.chargeTime += deltaTime;
            this.chargePulse = TimeManager.updatePhase(this.chargePulse, deltaTime, 15);
            
            // 更新瞄准线强度
            const chargeProgress = this.chargeTime / this.chargeDuration;
            this.aimLineAlpha = Math.min(0.8, chargeProgress * 1.2);
            this.aimLineIntensity = 0.5 + Math.sin(this.chargePulse) * 0.3;
            
            // 蓄力完成，发射激光
            if (this.chargeTime >= this.chargeDuration) {
                return this.fireLaser();
            }
        }
        
        return null; // 没有发射激光时返回null
    }
    
    startCharging(player) {
        this.isCharging = true;
        this.chargeTime = 0;
        // 简单预测：假设玩家继续当前方向移动
        // 由于我们无法直接获取玩家速度，就预测到当前位置
        this.predictedPlayerX = player.x + player.width / 2;
        this.predictedPlayerY = player.y + player.height / 2;
        
        // 计算从敌机到玩家的方向向量
        const startX = this.x + this.width / 2;
        const startY = this.y + this.height / 2;
        const dirX = this.predictedPlayerX - startX;
        const dirY = this.predictedPlayerY - startY;
        
        // 归一化方向向量
        const length = Math.sqrt(dirX * dirX + dirY * dirY);
        const normalizedDirX = dirX / length;
        const normalizedDirY = dirY / length;
        
        // 计算射线延伸到画布边界的终点
        // 使用一个很大的距离（比如14200像素）确保射线穿越整个画布
        this.targetX = startX + normalizedDirX * maxDistance;
        this.targetY = startY + normalizedDirY * maxDistance;
    }

    fireLaser() {
        // 计算激光发射点（从机身底部的主炮位置）
        const laserStartX = this.x + this.width / 2;
        const laserStartY = this.y + this.height * 0.9; // 从机身底部90%位置发射
        
        // 重新计算延伸方向（从新的起点到目标方向）
        const dirX = this.predictedPlayerX - laserStartX;
        const dirY = this.predictedPlayerY - laserStartY;
        const length = Math.sqrt(dirX * dirX + dirY * dirY);
        const normalizedDirX = dirX / length;
        const normalizedDirY = dirY / length;
        
        // 返回激光数据，由游戏主循环创建激光对象
        const laserData = {
            startX: laserStartX,
            startY: laserStartY,
            endX: laserStartX + normalizedDirX * maxDistance,
            endY: laserStartY + normalizedDirY * maxDistance,
            type: 'enemy'
        };
        
        // 重置攻击状态并设置发射后停顿
        this.isCharging = false;
        this.chargeTime = 0;
        this.lastAttackTime = Date.now();
        this.aimLineAlpha = 0;
        this.postFireDelay = this.postFireDuration; // 设置发射后停顿时间
        
        return laserData;
    }
    
    // 受击处理
    takeDamage() {
        this.hp--;
        this.damageFlash = 300; // 300毫秒闪烁效果
        return this.hp <= 0; // 返回是否被击毁
    }
    
    render(ctx) {
        ctx.save();
        
        // 受伤闪烁效果
        if (this.damageFlash > 0 && Math.floor(Date.now() / 100) % 2 === 0) {
            ctx.globalAlpha = 0.5;
        }
        
        // 绘制瞄准线（蓄力时显示）
        if (this.isCharging && this.aimLineAlpha > 0) {
            this.renderAimLine(ctx);
        }
        
        // 绘制护盾光环
        this.renderShieldEffect(ctx);
        
        // 绘制主体机身
        this.renderMainBody(ctx);
        
        // 绘制激光武器系统
        this.renderLaserWeapons(ctx);
        
        // 绘制引擎光效
        this.renderEngines(ctx);
        
        // 绘制装饰细节
        this.renderDecorations(ctx);
        
        // 绘制生命值指示器
        this.renderHealthBar(ctx);
        
        ctx.restore();
    }
    
    renderAimLine(ctx) {
        // 绘制激光瞄准预警线（射线延伸到很远）
        const alpha = this.aimLineAlpha * this.aimLineIntensity;
        // 与实际激光相同的起点位置（机身底部主炮位置）
        const startX = this.x + this.width / 2;
        const startY = this.y + this.height * 0.9;
        
        // 重新计算预警线的终点（从新起点到目标方向）
        const dirX = this.predictedPlayerX - startX;
        const dirY = this.predictedPlayerY - startY;
        const length = Math.sqrt(dirX * dirX + dirY * dirY);
        const normalizedDirX = dirX / length;
        const normalizedDirY = dirY / length;
        const aimEndX = startX + normalizedDirX * maxDistance;
        const aimEndY = startY + normalizedDirY * maxDistance;
        
        // 预警线主体（射线形式）
        ctx.strokeStyle = `rgba(255, 255, 0, ${alpha * 0.8})`;
        ctx.lineWidth = 3;
        ctx.setLineDash([10, 5]);
        ctx.beginPath();
        ctx.moveTo(startX, startY);
        ctx.lineTo(aimEndX, aimEndY);
        ctx.stroke();
        
        // 预警线光晕（更宽的射线）
        ctx.strokeStyle = `rgba(255, 200, 0, ${alpha * 0.4})`;
        ctx.lineWidth = 8;
        ctx.beginPath();
        ctx.moveTo(startX, startY);
        ctx.lineTo(aimEndX, aimEndY);
        ctx.stroke();
        
        // 重置线段样式
        ctx.setLineDash([]);
        
        // 在玄家预测位置显示目标点标记（不是在射线终点）
        // ctx.fillStyle = `rgba(255, 0, 0, ${alpha})`;
        // ctx.beginPath();
        // ctx.arc(this.predictedPlayerX, this.predictedPlayerY, 5 + Math.sin(this.chargePulse) * 2, 0, Math.PI * 2);
        // ctx.fill();
        
        // // 目标点外圈
        // ctx.strokeStyle = `rgba(255, 100, 0, ${alpha * 0.6})`;
        // ctx.lineWidth = 2;
        // ctx.beginPath();
        // ctx.arc(this.predictedPlayerX, this.predictedPlayerY, 12 + Math.sin(this.chargePulse * 1.5) * 3, 0, Math.PI * 2);
        // ctx.stroke();
    }
    
    renderShieldEffect(ctx) {
        // 重装甲护盾效果
        const shieldPulse = 0.6 + Math.sin(this.shieldPulse) * 0.4;
        const shieldRadius = 40 + Math.sin(this.shieldPulse * 1.5) * 3;
        
        const gradient = ctx.createRadialGradient(
            this.x + this.width/2, this.y + this.height/2, shieldRadius * 0.8,
            this.x + this.width/2, this.y + this.height/2, shieldRadius
        );
        
        gradient.addColorStop(0, `rgba(100, 100, 255, 0)`);
        gradient.addColorStop(0.8, `rgba(100, 100, 255, ${shieldPulse * 0.3})`);
        gradient.addColorStop(1, `rgba(100, 100, 255, 0)`);
        
        ctx.fillStyle = gradient;
        ctx.beginPath();
        ctx.arc(this.x + this.width/2, this.y + this.height/2, shieldRadius, 0, Math.PI * 2);
        ctx.fill();
        
        // 护盾能量环
        ctx.strokeStyle = `rgba(150, 150, 255, ${shieldPulse * 0.8})`;
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.arc(this.x + this.width/2, this.y + this.height/2, shieldRadius - 5, 0, Math.PI * 2);
        ctx.stroke();
    }
    
    renderMainBody(ctx) {
        // 重装甲机身
        ctx.shadowBlur = 12;
        ctx.shadowColor = '#6666ff';
        
        // 主机身（六角形重装甲设计）
        const bodyGradient = ctx.createRadialGradient(
            this.x + this.width/2, this.y + this.height/2, 0,
            this.x + this.width/2, this.y + this.height/2, this.width/2
        );
        bodyGradient.addColorStop(0, '#4444aa');
        bodyGradient.addColorStop(0.3, '#6666cc');
        bodyGradient.addColorStop(0.7, '#5555bb');
        bodyGradient.addColorStop(1, '#333399');
        
        ctx.fillStyle = bodyGradient;
        
        // 六角形机身
        ctx.beginPath();
        const centerX = this.x + this.width / 2;
        const centerY = this.y + this.height / 2;
        const radius = this.width / 2.5;
        
        for (let i = 0; i < 6; i++) {
            const angle = (i / 6) * Math.PI * 2 - Math.PI / 2;
            const px = centerX + Math.cos(angle) * radius;
            const py = centerY + Math.sin(angle) * radius;
            
            if (i === 0) {
                ctx.moveTo(px, py);
            } else {
                ctx.lineTo(px, py);
            }
        }
        ctx.closePath();
        ctx.fill();
        
        // 机身装甲板
        ctx.strokeStyle = '#8888ff';
        ctx.lineWidth = 2;
        ctx.stroke();
        
        // 中央控制室
        ctx.fillStyle = '#2222aa';
        ctx.beginPath();
        ctx.arc(centerX, centerY, radius * 0.4, 0, Math.PI * 2);
        ctx.fill();
        
        ctx.shadowBlur = 0;
    }
    
    renderLaserWeapons(ctx) {
        // 激光武器系统
        const centerX = this.x + this.width / 2;
        const centerY = this.y + this.height / 2;
        const pulse = 0.7 + Math.sin(this.enginePulse * 1.5) * 0.3;
        
        // 主激光炮（朝下）
        const mainGunGradient = ctx.createLinearGradient(
            centerX - 8, centerY + 10,
            centerX + 8, centerY + 30
        );
        mainGunGradient.addColorStop(0, '#666666');
        mainGunGradient.addColorStop(0.5, '#999999');
        mainGunGradient.addColorStop(1, '#555555');
        
        ctx.fillStyle = mainGunGradient;
        ctx.fillRect(centerX - 8, centerY + 10, 16, 20);
        
        // 激光炮边框
        ctx.strokeStyle = '#aaaaaa';
        ctx.lineWidth = 1;
        ctx.strokeRect(centerX - 8, centerY + 10, 16, 20);
        
        // 蓄力时的充能效果
        if (this.isCharging) {
            const chargeIntensity = (this.chargeTime / this.chargeDuration);
            const chargePulse = 0.5 + Math.sin(this.chargePulse) * 0.5;
            
            // 充能光芒
            ctx.fillStyle = `rgba(255, 100, 0, ${chargeIntensity * chargePulse * 0.8})`;
            ctx.fillRect(centerX - 6, centerY + 12, 12, 16);
            
            // 充能粒子效果
            for (let i = 0; i < 8; i++) {
                const angle = (i / 8) * Math.PI * 2;
                const distance = 20 + Math.sin(this.chargePulse + i) * 5;
                const px = centerX + Math.cos(angle) * distance;
                const py = centerY + Math.sin(angle) * distance;
                
                ctx.fillStyle = `rgba(255, 200, 0, ${chargeIntensity * chargePulse})`;
                ctx.beginPath();
                ctx.arc(px, py, 2, 0, Math.PI * 2);
                ctx.fill();
            }
        }
        
        // 发射激光时的发射口特效
        if (this.postFireDelay > 0) {
            const fireIntensity = this.postFireDelay / this.postFireDuration;
            const firePulse = 0.7 + Math.sin(Date.now() / 50) * 0.3; // 快速闪烁
            
            // 发射口白光效果
            ctx.fillStyle = `rgba(255, 255, 255, ${fireIntensity * firePulse})`;
            ctx.beginPath();
            ctx.arc(centerX, centerY + this.height * 0.4, 8, 0, Math.PI * 2); // 在主炮底部
            ctx.fill();
            
            // 发射口光晕
            ctx.fillStyle = `rgba(255, 100, 100, ${fireIntensity * firePulse * 0.5})`;
            ctx.beginPath();
            ctx.arc(centerX, centerY + this.height * 0.4, 12, 0, Math.PI * 2);
            ctx.fill();
        }
        
        // 散热器
        ctx.fillStyle = '#444444';
        const coolerPositions = [
            {x: centerX - 20, y: centerY},
            {x: centerX + 20, y: centerY},
            {x: centerX - 15, y: centerY - 15},
            {x: centerX + 15, y: centerY - 15}
        ];
        
        for (let pos of coolerPositions) {
            ctx.fillRect(pos.x - 3, pos.y - 8, 6, 16);
            
            // 散热效果
            if (this.isCharging) {
                ctx.fillStyle = `rgba(255, 100, 0, ${pulse * 0.3})`;
                ctx.fillRect(pos.x - 2, pos.y - 6, 4, 12);
            }
        }
    }
    
    renderEngines(ctx) {
        // 重装推进器（向上喷射）
        // 在蓄力或发射后停顿时减弱引擎效果
        const isStationary = this.isCharging || this.postFireDelay > 0;
        const basePulse = 0.7 + Math.sin(this.enginePulse) * 0.3;
        const pulse = isStationary ? basePulse * 0.3 : basePulse; // 停止时引擎效果减弱
        const baseFlameLength = 15 + Math.sin(this.enginePulse * 1.5) * 5;
        const flameLength = isStationary ? baseFlameLength * 0.2 : baseFlameLength; // 停止时火焰更短
        
        const enginePositions = [
            this.x + this.width * 0.25,
            this.x + this.width * 0.5,
            this.x + this.width * 0.75
        ];
        
        for (let engineX of enginePositions) {
            const engineY = this.y;
            
            // 推进器火焰（向上）
            const engineGradient = ctx.createLinearGradient(
                engineX, engineY, engineX, engineY - flameLength
            );
            
            if (isStationary) {
                // 停止状态时显示更暗的蓝色（低功率模式）
                engineGradient.addColorStop(0, `rgba(50, 50, 150, ${pulse})`);
                engineGradient.addColorStop(0.3, `rgba(80, 80, 180, ${pulse * 0.8})`);
                engineGradient.addColorStop(0.7, `rgba(100, 100, 200, ${pulse * 0.6})`);
                engineGradient.addColorStop(1, 'rgba(50, 50, 100, 0)');
            } else {
                // 正常移动时的明亮蓝色
                engineGradient.addColorStop(0, `rgba(100, 100, 255, ${pulse})`);
                engineGradient.addColorStop(0.3, `rgba(150, 150, 255, ${pulse * 0.8})`);
                engineGradient.addColorStop(0.7, `rgba(200, 200, 255, ${pulse * 0.6})`);
                engineGradient.addColorStop(1, 'rgba(100, 100, 200, 0)');
            }
            
            ctx.fillStyle = engineGradient;
            ctx.fillRect(engineX - 4, engineY - flameLength, 8, flameLength);
            
            // 推进器本体
            ctx.fillStyle = '#333333';
            ctx.fillRect(engineX - 3, engineY, 6, 5);
        }
    }
    
    renderDecorations(ctx) {
        // 装甲细节和标识
        const centerX = this.x + this.width / 2;
        const centerY = this.y + this.height / 2;
        const pulse = 0.8 + Math.sin(this.enginePulse * 1.5) * 0.2;
        
        // 状态指示灯
        const lights = [
            {x: centerX - 15, y: centerY - 20, color: this.isCharging ? '#ff6600' : '#0066ff'},
            {x: centerX + 15, y: centerY - 20, color: this.isCharging ? '#ff6600' : '#0066ff'},
            {x: centerX - 15, y: centerY + 20, color: this.hp > 5 ? '#00ff00' : '#ff0000'},
            {x: centerX + 15, y: centerY + 20, color: this.hp > 5 ? '#00ff00' : '#ff0000'}
        ];
        
        for (let light of lights) {
            ctx.fillStyle = light.color.replace(')', `, ${pulse})`).replace('rgb', 'rgba');
            ctx.beginPath();
            ctx.arc(light.x, light.y, 2, 0, Math.PI * 2);
            ctx.fill();
        }
        
        // 装甲接缝线
        ctx.strokeStyle = `rgba(150, 150, 200, ${pulse * 0.6})`;
        ctx.lineWidth = 1;
        
        // 水平接缝
        ctx.beginPath();
        ctx.moveTo(this.x + 10, centerY);
        ctx.lineTo(this.x + this.width - 10, centerY);
        ctx.stroke();
        
        // 垂直接缝
        ctx.beginPath();
        ctx.moveTo(centerX, this.y + 10);
        ctx.lineTo(centerX, this.y + this.height - 10);
        ctx.stroke();
    }
    
    renderHealthBar(ctx) {
        // 生命值条
        const barWidth = this.width;
        const barHeight = 6;
        const barX = this.x;
        const barY = this.y - 15;
        
        // 背景
        ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
        ctx.fillRect(barX, barY, barWidth, barHeight);
        
        // 生命值
        const healthPercent = this.hp / this.maxHp;
        let healthColor = '#ff0000';
        if (healthPercent > 0.7) healthColor = '#00ff00';
        else if (healthPercent > 0.3) healthColor = '#ffaa00';
        
        ctx.fillStyle = healthColor;
        ctx.fillRect(barX + 1, barY + 1, (barWidth - 2) * healthPercent, barHeight - 2);
        
        // 边框
        ctx.strokeStyle = '#ffffff';
        ctx.lineWidth = 1;
        ctx.strokeRect(barX, barY, barWidth, barHeight);
        
        // 类型标识
        ctx.fillStyle = '#ffffff';
        ctx.font = '10px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('SNIPER', this.x + this.width/2, this.y - 20);
    }
}